package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.sys.models.dto.SysRoleDTO;
import com.yt.sys.models.dto.SysUserDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import com.yt.sys.models.service.ISysRoleService;
import com.yt.sys.models.service.ISysUserRoleService;
import com.yt.sys.models.service.ISysUserService;
import com.yt.sys.models.bo.SysUserRoleBO;
import com.yt.sys.models.dto.SysUserRoleDTO;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户角色关联信息控制器
 *
 * @author yzz
 * @Date 2025-09-03 14:10:59
 */

@RestController
@RequestMapping("/api/sysUserRole")
@Slf4j
@Api(value = "SysUserRoleApiController",tags = "用户角色关联信息Api接口")
public class SysUserRoleApiController {

    @DubboReference
    private ISysUserRoleService sysUserRoleService;
    
    @DubboReference
    private ISysUserService sysUserService;
    
    @DubboReference
    private ISysRoleService sysRoleService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<SysUserRoleDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SysUserRoleDTO dto = sysUserRoleService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "用户角色关联信息列表",notes = "用户角色关联信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<SysUserRoleDTO>> queryPageList(SysUserRoleBO bo){
        Wrapper<SysUserRoleDTO> wrapper = new EntityWrapper<>();
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<SysUserRoleDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = sysUserRoleService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    @ApiModel(value = "用户角色分配请求对象", description = "用户角色分配请求对象")
    @Data
    public static class AssignRoleRequest implements Serializable {
        @ApiModelProperty(value = "用户ID", required = true, example = "123")
        private Long userId;
        
        @ApiModelProperty(value = "角色ID", required = true, example = "456")
        private Long roleId;
    }

    @ApiOperation(value = "分配角色", notes = "为用户分配角色")
    @PostMapping("/assignRole")
    public Result<String> assignRole(@RequestBody AssignRoleRequest request) {
        // 验证参数
        if (request.getUserId() == null || request.getRoleId() == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "用户ID和角色ID不能为空");
        }

        // 验证用户是否存在
        if (sysUserService.selectById(request.getUserId()) == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "用户不存在");
        }

        // 验证角色是否存在
        if (sysRoleService.selectById(request.getRoleId()) == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "角色不存在");
        }

        // 检查用户是否已经有关联的角色
        Wrapper<SysUserRoleDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", request.getUserId());
        List<SysUserRoleDTO> existList = sysUserRoleService.selectList(wrapper);
        
        Date now = new Date();
        
        if (existList != null && !existList.isEmpty()) {
            // 用户已有角色，更新现有记录
            SysUserRoleDTO existingRole = existList.get(0);
            existingRole.setRoleId(request.getRoleId());
            existingRole.setUpdateTime(now);
            // 乐观锁版本号增加
            existingRole.setRevision(existingRole.getRevision() + 1);
            
            boolean result = sysUserRoleService.updateById(existingRole);
            if (result) {
                return new Result<>(CodeEnum.SUCCESS.getCode(), "角色分配成功", null);
            } else {
                return new Result<>(CodeEnum.FAIL_100007.getCode(), "角色分配失败");
            }
        } else {
            // 用户没有角色，创建新的用户角色关联记录
            SysUserRoleDTO sysUserRoleDTO = new SysUserRoleDTO();
            sysUserRoleDTO.setUserId(request.getUserId());
            sysUserRoleDTO.setRoleId(request.getRoleId());
            sysUserRoleDTO.setRevision(0);
            
            // 设置创建时间和更新时间
            sysUserRoleDTO.setCreateTime(now);
            sysUserRoleDTO.setUpdateTime(now);
            
            boolean result = sysUserRoleService.insert(sysUserRoleDTO);
            if (result) {
                return new Result<>(CodeEnum.SUCCESS.getCode(), "角色分配成功", null);
            } else {
                return new Result<>(CodeEnum.FAIL_100007.getCode(), "角色分配失败");
            }
        }
    }

    @ApiModel(value = "用户ID请求对象", description = "用户ID请求对象")
    @Data
    public static class UserIdRequest implements Serializable {
        @ApiModelProperty(value = "用户ID", required = true, example = "123")
        private Long userId;
    }

    @ApiOperation(value = "根据用户ID获取用户角色名", notes = "通过用户表、角色表、用户角色关联表进行多表联查，根据用户ID返回角色名")
    @PostMapping("/getUserRoles")
    public Result<String> getUserRolesAPI(@RequestBody UserIdRequest request) {
        // 参数校验
        if (request.getUserId() == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "用户ID不能为空");
        }

        // 验证用户是否存在
        SysUserDTO user = sysUserService.selectById(request.getUserId());
        if (user == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "用户不存在");
        }

        // 查询用户角色关联信息
        Wrapper<SysUserRoleDTO> userRoleWrapper = new EntityWrapper<>();
        userRoleWrapper.eq("user_id", request.getUserId());
        List<SysUserRoleDTO> userRoles = sysUserRoleService.selectList(userRoleWrapper);

        if (userRoles == null || userRoles.isEmpty()) {
            return new Result<>(CodeEnum.FAIL.getCode(), "用户未分配角色");
        }

        // 获取角色ID（取第一个）
        Long roleId = userRoles.get(0).getRoleId();

        // 查询角色信息
        SysRoleDTO role = sysRoleService.selectById(roleId);
        if (role == null) {
            return new Result<>(CodeEnum.FAIL.getCode(), "角色信息不存在");
        }

        // 返回角色名
        return new Result<>(CodeEnum.SUCCESS.getCode(), "查询成功", role.getRoleName());
    }

   
}